package sample.googlecode.genericdao.oldworld.web;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.commons.beanutils.BeanUtils;

import com.javaframe.role.entity.User;
import com.javaframe.role.service.UserService;




@Controller
public class UserController {
	UserService userService;
	
	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@RequestMapping(method=RequestMethod.POST, value="/users")
	@ResponseBody
	public Map<String, Object> getUsers(@RequestBody Map<String, Object> map){ 
		List<User> users=userService.findAll();
	    Map<String, Object> userVo = new HashMap<String, Object>();
	    userVo.put("identifier", "userId");
	    userVo.put("items", users);
	    return userVo;
    }
	
	@RequestMapping(method=RequestMethod.POST, value="/user/create")
	@ResponseBody
	public void addUser(@RequestBody Map<String, Object> map) throws IllegalAccessException, InvocationTargetException{ 
		User user = new User();
		BeanUtils.copyProperties(user, map);
        userService.save(user);
    }
	
	//@RequestMapping(method=RequestMethod.POST, value="/user/fetch/{id}")
	//@ResponseBody
	//public User getUser(@PathVariable Integer id) throws IllegalAccessException, InvocationTargetException{ 
		//User user = new User();
		//BeanUtils.copyProperties(user, map);
       // return userService.findById(id.longValue());
   // }
	
	@RequestMapping(method=RequestMethod.POST, value="/user/update/{id}")
	@ResponseBody
	public void updateUser(@RequestBody Map<String, Object> map,@PathVariable Integer id) throws IllegalAccessException, InvocationTargetException{ 
		//User user=userService.findById(id.longValue());
		User user=new User();
		BeanUtils.copyProperties(user, map);
		//user.setUserId(id.longValue());
        userService.save(user);
    }
	
	@RequestMapping(method=RequestMethod.POST, value="/user/delete")
	@ResponseBody
	public void deleteUser(@RequestBody Map<String, Object> map) throws IllegalAccessException, InvocationTargetException{ 
		List<?> items=(List<?>)map.get("items");
		for(int i=0;i<items.size();i++){
			 Integer id=Integer.valueOf(((Map<String, Object>)items.get(i)).get("userId").toString()); 
			// userService.delete(id.longValue());
			// User user=userService.findById(id.longValue());
			// userService.delete(user.getUserId());
		}
    }
}
